<?php

namespace app\admin\model\deerhome;

use think\Model;
use think\Db;
use app\admin\model\deerhome\CardOrderItems;
use app\admin\model\deerhome\OrderPayLog;
use app\admin\model\deerhome\Card;

class CardOrder extends Model
{

    // 表名
    protected $name = 'deerhome_card_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
        ,'time_area_text'
        ,'left_day_text'
        ,'left_num_percent'
    ];
    
    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $row->add_time=date('Y-m-d H:i:s');
        });
        self::beforeWrite(function ($row) {
            if(isset($row->num_left) && $row->num_left<0){
                $row->num_left=0;
            }
        });
        self::beforeDelete(function ($row) {
            if ($row->status !=1) {
                throw new \think\Exception(__('待支付的订单才可以删除'));
                return false;
            }
        });
        self::afterDelete(function ($row) {
            $pk = $row->getPk();
            CardOrderItems::where('deerhome_card_order_id', $row[$pk])->delete();
            OrderPayLog::where('order_sn', $row['sn'])->where('type',4)->delete();
        });
    }
    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }
    public function getTimeAreaTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['time_area']) ? $data['time_area'] : '');
        $list = (new Card)->getTimeAreaList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getLeftDayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        //计算剩余天数
        $left_day=0;
        if($value){
            $left_day=ceil((strtotime($value)-time())/86400);
        }
        return $left_day;
    }


    public function getLeftNumPercentAttr($value, $data)
    {
        if($data['num_total']>0){
            return round($data['num_left']/$data['num_total']*100,2);
        }
        return 0;
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function card()
    {
        return $this->belongsTo('app\admin\model\deerhome\Card', 'deerhome_card_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function orderItems()
    {
        return $this->hasMany('app\admin\model\deerhome\CardOrderItems', 'deerhome_card_order_id','id');
    }
    public function orderPayLog()
    {
        return $this->hasMany('app\admin\model\deerhome\OrderPayLog', 'order_sn','sn')->order('id desc');
    }
    public function order()
    {
        return $this->hasMany('app\admin\model\deerhome\Order', 'card_order_id','id')->order('id desc');
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\deerhome\User', 'deerhome_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 订单支付成功
    */
    public function payed($sn,$payway,$paytime,$upateOrder=[]){
        $order=$this->where("sn",$sn)->where("status",1)->find();
        if(!$order){
            throw new \Exception("订单不存在或已支付");
        }
        $need_pay=$order['price_need_pay'];

        $upateOrder['status']=2;
        $upateOrder['num_total']=(new CardOrderItems)->where('deerhome_card_order_id',$order['id'])->sum('num');
        $upateOrder['num_left']=$upateOrder['num_total'];
        $upateOrder['pay_time']=$paytime;
        $upateOrder['price_payed']=$need_pay;
        $upateOrder['start_time']=$upateOrder['pay_time'];
        $upateOrder['end_time']=(new Card)->getTimeAreaEndTime($upateOrder['start_time'],$order['time_area']);

        //更新分佣
        if($order['agent_lev1_percent']>0){
            $upateOrder['agent_lev1_price']=bcdiv(bcmul($order['price_need_pay'],$order['agent_lev1_percent'],2),100,2);
        }
        if($order['agent_lev2_percent']>0){
            $upateOrder['agent_lev2_price']=bcdiv(bcmul($order['price_need_pay'],$order['agent_lev2_percent'],2),100,2);
        }
        //支付流水日志
        $payLog=[
            'price'=>$need_pay*-1,
            'pay_time'=>$paytime,
            'status'=>2,
            'is_wallet'=>($payway=='储值卡支付')?1:2,
            'payway_type'=>1,
            'pay_way'=>$payway,
            'note'=>"订单{$order['sn']}"
        ];

        $order->save($upateOrder);
        CardOrderItems::where('deerhome_card_order_id',$order['id'])->update(['num_left'=>Db::raw('num')]);
        Card::where('id',$order['deerhome_card_id'])->setInc('sale_times');
        OrderPayLog::where('order_sn',$order['sn'])->where('type',3)->update($payLog);
    }
}
